package com.zjp.proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: zjp
 * @date: 2023-12-03
 * @description: 创建代理对象工具类
 */
public class ProxyUtil {
    /**
     * @author zjp
     * @date 2023/12/3
     * @description 创建一个被代理对象的代理对象
     * @param userService 被代理对象
     * @return UserService 代理对象
     */
    public static UserService createUserServiceProxy(UserService userService){
        UserService userServiceProxy = (UserService)Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                new Class[]{UserService.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 要代理的方法名称
                        List<String> proxyMethods = Arrays.asList("login", "getUserInfo", "removeUserById");
                        String methodName = method.getName();
                        if (proxyMethods.contains(methodName)){
                            long startTime = System.currentTimeMillis();

                            Object result = method.invoke(userService, args);// 执行被代理对象的方法

                            long endTime = System.currentTimeMillis();

                            System.out.println("执行"+methodName+"方法耗时：" + (endTime - startTime));
                            return result;
                        }else {
                            Object result = method.invoke(userService, args);// 执行被代理对象的方法
                            return result;
                        }
                    }
                });

        return userServiceProxy;
    }
}
